package controller

import (
	"errors"
	"fmt"
	"github.com/gorilla/websocket"
	"github.com/sirupsen/logrus"
	"log"
	"my-desktop/common"
	"my-desktop/models"
	"my-desktop/sshTerm"
	"net/http"
	"os"
	"time"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin:     func(r *http.Request) bool { return true },
}

func WSConnect(w http.ResponseWriter, r *http.Request) {
	_ = r.ParseForm()
	clientName := r.Form.Get("name")
	userID := r.Form.Get("userID")
	if len(clientName) == 0 {
		logrus.Warn("没有客户端名称clientName")
		common.Error(w, models.HasNoAuth, "", errors.New("用户没有权限访问"))
		return
	}
	if len(userID) == 0 {
		logrus.Warn("没有用户ID")
		common.Error(w, models.HasNoAuth, "", errors.New("用户没有权限访问"))
		return
	}

	// 生成mapkey
	redisKey := "client:" + userID + ":" + clientName
	fmt.Println("redisKey: ", redisKey)

	id := r.Header.Get("Sec-WebSocket-Key")
	//fmt.Println(id)

	webssh := sshTerm.NewWebSSH()
	webssh.SetTerm(sshTerm.TermXterm) // term 可以使用 ansi, linux, vt100, xterm, dumb，除了 dumb外其他都有颜色显示, 默认 xterm
	webssh.SetBuffSize(8192)
	webssh.SetId(id)
	webssh.SetConnTimeOut(5 * time.Second)
	webssh.SetLogger(log.New(os.Stderr, "[webssh] ", log.Ltime|log.Ldate))

	// 是否启用 sz 与 rz
	//webssh.DisableSZ()
	//webssh.DisableRZ()

	upGrader := websocket.Upgrader{
		// cross origin domain
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
		// 处理 Sec-WebSocket-Protocol Header
		//Subprotocols: []string{r.Header.Get("Sec-WebSocket-Protocol")},
		Subprotocols:    []string{"webssh"},
		ReadBufferSize:  8192,
		WriteBufferSize: 8192,
	}

	ws, err := upGrader.Upgrade(w, r, nil)
	if err != nil {
		logrus.Error("websocket create error", err)
	}

	//ws.SetCompressionLevel(4)
	//ws.EnableWriteCompression(true)

	webssh.AddWebsocket(ws, redisKey)

}
